package com.aiss.ws.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

/**
 * Created by WHY on 2015/8/5 11:38
 * Copyright (c) 2015年 Beijing Yunshan Information Technology Co., Ltd. All rights reserved.
 */
public class CommonUtils {
    private static Context context;

    public static void setContext(Context context) {
        CommonUtils.context = context;
    }

    public static String getString(int id){
        checkContext();
        return context.getResources().getString(id);
    }

    public static boolean checkNet(final Context mActivity) {
        if (!isNetworkAvailable(mActivity)) {
            AlertDialog.Builder builders = new AlertDialog.Builder(mActivity);
            builders.setTitle("抱歉，网络连接失败，是否进行网络设置？");
            builders.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // 进入无线网络配置界面
                            mActivity.startActivity(new Intent(
                                    Settings.ACTION_WIRELESS_SETTINGS));
                        }
                    });
            builders.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int whichButton) {
                            // 关闭当前activity
                            ((Activity)mActivity).finish();
                        }
                    });
            builders.show();
            return false;
        }
        return true;

    }

    // 检测网络是否可用
    public static boolean isNetworkAvailable(Context mActivity) {
        Context context = mActivity.getApplicationContext();
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private static void checkContext(){
        if (context == null)
            throw new RuntimeException("请先设置应用上下文环境!!");
    }
}
